import socket
import threading


class HttpWebServer(object):
    def __init__(self):
        tcp_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        tcp_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,True)
        tcp_socket.bind(("",8080))
        tcp_socket.listen(128)
        self.tcp_socket = tcp_socket

    def run(self):
        while True:
            new_socket,new_address = self.tcp_socket.accept()
            threading.Thread(target=self.func,args=(new_socket,new_address),daemon=True).start()

    @staticmethod
    def func(new_socket,new_address):
        print(f"{str(new_address)}上线了")
        recv_data = new_socket.recv(4096)
        if not recv_data:
            print(f"{str(new_address)}已断开连接")
            new_socket.close()
            return
        show_info = recv_data.decode().split(" ")[1]
        print(show_info)
        if show_info == "/":
            show_info = "/index.html"

        try:
            with open("baoke" + show_info,"rb") as file:
                file_data = file.read()
        except:
            with open("baoke/404.html","rb") as file:
                file_data = file.read()
            html_data = "HTTP/1.1 404 NotFind\r\nServer: PWS\r\n\r\n".encode() + file_data
        else:
            html_data = "HTTP/1.1 200 OK\r\nServer: PWS\r\n\r\n".encode() + file_data
        finally:
            new_socket.send(html_data)
            new_socket.close()

if __name__ == '__main__':
    http = HttpWebServer()
    http.run()